package com.lee.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lee.http.SpringBeanContext;
import com.lee.member.api.service.UserLoginService;
import com.lee.member.config.UnionLoginConfig;
import com.lee.member.entity.MemberUser;
import com.lee.member.entity.UnionLogin;
import com.lee.member.mapper.UnionLoginMapper;
import com.lee.member.strategy.UnionLoginStrategy;
import com.lee.response.ResponseResult;
import com.lee.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.json.Json;

/**
 * 用户登录根据令牌
 * @author zfl_a
 * @date 2020/4/5
 * @project login-authorization-parent
 */
@RestController
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private TokenUtils tokenUtils ;
    @Autowired
    private UnionLoginMapper unionLoginMapper ;
    @Autowired
    private UnionLoginConfig unionLoginConfig ;

    @Override
    public ResponseResult loginByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        // 根据token获取openId和联合登录id
        String tokenValue = tokenUtils.getTokenValue(token);
        if (StringUtils.isEmpty(tokenValue)) {
            return new ResponseResult(400,"token失效",null);
        }
        // 2.根据openid 查询是否关联
        JSONObject tokenJsonObject = JSONObject.parseObject(tokenValue);

        String publicId = tokenJsonObject.getString(unionLoginConfig.getPublicIdKey());

        //获取渠道详细信息
        UnionLogin unionLogin = unionLoginMapper.selectByUnionLoginId(publicId);
        if (unionLogin == null) {
            return new ResponseResult(400,"该渠道不存在或者已关闭",null);
        }
        String unionBeanId = unionLogin.getUnionBeanId();
        UnionLoginStrategy unionLoginStrategy = SpringBeanContext.
                getBean(unionBeanId, UnionLoginStrategy.class);
        if (unionLoginStrategy == null) {
            return new ResponseResult(400,"该策略类不存在",null);
        }
        String openId = tokenJsonObject.getString(unionLoginConfig.getOpenIdKey());

        MemberUser memberUser = unionLoginStrategy.queryUser(openId);
        if (memberUser == null) {
            JSONObject erroRetuen = new JSONObject();
            erroRetuen.put(unionLoginConfig.getOpenIdKey(),openId);
            erroRetuen.put(unionLoginConfig.getPublicIdKey(),unionLogin.getUnionPublicId());
            //可以自定义响应码 关联、注册根据实际业务定义
            return new ResponseResult(400,"当前用户未关联数据，跳转界面关联",erroRetuen);
        }
        //如果已经关联，实现自动登录
        String userId = memberUser.getUserId();
        String userToken = tokenUtils.createToken(unionLoginConfig.getUserTokenPrefix(), userId);
        JSONObject resultData = new JSONObject();
        resultData.put("userToken", userToken);
        return new ResponseResult(200,"登录成功",resultData);
    }
}
